package com.example.nettydemo.file;

import com.example.nettydemo.codec.msgpack.MsgpackDecoder;
import com.example.nettydemo.codec.msgpack.MsgpackEncoder;
import com.example.nettydemo.decoder.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 自动完成以分隔符做结束标志的消息的解码
 */
public class HttpFileServer {

    private static final String DEFAULT_URL = "/src/main/java/com/example/nettydemo";

    public void bind(int port, String url) throws InterruptedException {
        // 用于服务端接收客户端的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        // 用于进行socketChannel的网络读写
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());

                            // 将多个消息转换为单一的FullHttpRequest 或者FullHttpResponse
                            socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                            socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());

                            // 支持异步发送大的码流, 但不占用过多的内存, 防止发生java内存溢出错误
                            socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                            socketChannel.pipeline().addLast(new HttpFileServerHandler(url));
                        }
                    });

            // 等待绑定操作完成
            ChannelFuture channelFuture = serverBootstrap.bind("192.168.110.1", port).sync();

            // 等待服务端的链路关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        String url = DEFAULT_URL;
        if(args.length > 1){
            url = args[1];
        }

        new HttpFileServer().bind(port, url);
    }
}
